package com.zmkj.cn.comm.util;


import com.zmkj.cn.comm.vo.TreeVo;
import org.apache.commons.lang3.StringUtils;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
/**
 * 树结构工具类
 * @author 伍绍宇 Coy
 * @date 2021年4月19日 11:37:13
 */
public class TreeUtil {

    /**
     * 获取主级菜单
     * @param treeVos
     * 
     */
    public static List<TreeVo> createCheckTree(List<TreeVo> treeVos) {
        //创建上级部门并把待组装的数据删除掉
        List<TreeVo> parentList=new ArrayList<>();
        for (Iterator<TreeVo> iterator = treeVos.iterator(); iterator.hasNext(); ) {
            TreeVo next = iterator.next();
            if(next.getParentId()==null){
                parentList.add(next);
                iterator.remove();
            }
        }
        for (TreeVo treeVo : parentList) {
            treeVo.setChildren(createChildList(treeVo.getValue(),treeVos));
        }
        return parentList;
    }

    public static List<TreeVo> createChildList(String value, List<TreeVo> treeVos) {
        List<TreeVo> children=new ArrayList<>();
        if(treeVos.size()==0){
            return children;
        }
        for (Iterator<TreeVo> iterator = treeVos.iterator(); iterator.hasNext(); ) {
            TreeVo next = iterator.next();
            if(StringUtils.equals(next.getParentId(),value)){
                iterator.remove();
                children.add(next);
            }
            if(StringUtils.isBlank(next.getParentId())){
                iterator.remove();
            }
        }
        for (TreeVo child : children) {
            child.setChildren(createChildList(child.getValue(),treeVos));
        }
        return children;
    }
}
